package com.zy.business.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.business.domain.TbReportUser;
import com.zy.business.domain.TbWorkReport;
import com.zy.business.mapper.WorkReportMapper;
import com.zy.business.service.ReportUserService;
import com.zy.business.service.WorkReportService;
import com.zy.common.core.domain.AjaxResult;
import com.zy.common.core.domain.entity.SysDept;
import com.zy.common.core.domain.entity.SysUser;
import com.zy.common.core.text.Convert;
import com.zy.common.utils.DateUtil;
import com.zy.common.utils.SecurityUtils;
import com.zy.common.utils.WebUtil;
import com.zy.system.service.ISysDeptService;
import com.zy.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @description: 工作汇报实现类
 * @author: whf
 * @create: 2023-02-23 15:47
 **/
@Service
public class WorkReportServiceImpl extends ServiceImpl<WorkReportMapper, TbWorkReport> implements WorkReportService {

    @Autowired
    private ReportUserService reportUserService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Value("${APPID}")
    private String APPID;

    @Value("${APPSECRET}")
    private String APPSECRET;

    @Value("${REPORT_REMIND}")
    private String remindTempId;


    @Override
    @Transactional
    public AjaxResult addWorkReport(TbWorkReport workReport) {
        workReport.setCreateTime(new Date());
        workReport.setCreateUser(SecurityUtils.getUserId());
        workReport.setCreateBy(SecurityUtils.getUsername());
        workReport.setContent(workReport.getContent());
        if(workReport.getReportDate()==null){
            workReport.setReportDate(new Date());
        }
        baseMapper.insert(workReport);
        for (Long id : Convert.toLongArray(workReport.getSendUser())) {
            TbReportUser reportUser = new TbReportUser();
            reportUser.setReportId(workReport.getId());
            reportUser.setUserId(id);
            if (workReport.getIsNotice()==1){
                SysUser user = userService.selectUserById(id);
                this.sendMessage(user,workReport);
            }
            reportUserService.save(reportUser);
        }
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public AjaxResult editWorkReport(TbWorkReport workReport) {
        TbWorkReport old = baseMapper.selectById(workReport.getId());
        List<TbReportUser> reportUserList = reportUserService.list(new QueryWrapper<TbReportUser>().eq("report_id",workReport.getId()).eq("is_read",1));
        if (reportUserList!=null && reportUserList.size()>0){
            return AjaxResult.error(507,"该条工作汇报已读，不能编辑！");
        }
        reportUserService.remove(new QueryWrapper<TbReportUser>().eq("report_id", workReport.getId()));
        for (Long id : Convert.toLongArray(workReport.getSendUser())) {
            TbReportUser reportUser = new TbReportUser();
            reportUser.setReportId(workReport.getId());
            reportUser.setUserId(id);
            if (workReport.getIsNotice()==1 && old.getIsNotice()==0){
                SysUser user = userService.selectUserById(id);
                this.sendMessage(user,workReport);
            }
            reportUserService.save(reportUser);
        }
        old.setUpdateTime(new Date());
        old.setUpdateBy(SecurityUtils.getUsername());
        old.setContent(workReport.getContent());
        old.setSendUser(workReport.getSendUser());
        old.setReportDate(workReport.getReportDate());
        old.setIsNotice(workReport.getIsNotice());
        baseMapper.updateById(old);
        return AjaxResult.success();
    }

    public List<TbWorkReport> list(String type) {
        Long userId = null;
        Long copyId = null;
        if ("copy".equals(type)) {
            copyId = SecurityUtils.getUserId();
        }else {
            userId = SecurityUtils.getUserId();
        }
        List<TbWorkReport> workReportList = this.baseMapper.getList(userId,copyId);
        return workReportList;
    }

    /**
     * {{first.DATA}}
     * 汇报人：{{keyword1.DATA}}
     * 汇报时间：{{keyword2.DATA}}
     * 汇报类型：{{keyword3.DATA}}
     * 部门名称：{{keyword4.DATA}}
     * 组织名称：{{keyword5.DATA}}
     * {{remark.DATA}}
     */
    public void sendMessage(SysUser user,TbWorkReport workReport){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SysUser sendUser = userService.selectUserByUserName(workReport.getCreateBy());
        SysDept dept = deptService.selectDeptById(sendUser.getDeptId());
        String accessUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET;
        JSONObject result = WebUtil.doGet(accessUrl);
        String accessToken = null;
        if (null != result) {
            accessToken = result.getString("access_token");
        }
        String templtUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", user.getOpenId());   // openid
        jsonObject.put("template_id", remindTempId);
        jsonObject.put("url", "http://kq.heshenghua.net/office/#/workHbDetail?openId="+user.getOpenId()+"&reportId="+workReport.getId()+"&userId="+user.getUserId());

        JSONObject data = new JSONObject();
        JSONObject first = new JSONObject();
        first.put("value", "您好，您收到一份工作汇报");
        first.put("color", "#173177");
        //发送人
        JSONObject keyword1 = new JSONObject();
        keyword1.put("value", workReport.getCreateBy());
        keyword1.put("color", "#173177");
        //发送时间
        JSONObject keyword2 = new JSONObject();
        keyword2.put("value", sdf.format(workReport.getCreateTime()));
        keyword2.put("color", "#173177");

        JSONObject keyword3 = new JSONObject();
        keyword3.put("value", "工作汇报");
        keyword3.put("color", "#173177");

        JSONObject keyword4 = new JSONObject();
        keyword4.put("value", dept.getDeptName());
        keyword4.put("color", "#173177");

        JSONObject remark = new JSONObject();
        remark.put("value", "点击查看详情");
        remark.put("color", "#173177");

        data.put("first",first);
        data.put("keyword1",keyword1);
        data.put("keyword2",keyword2);
        data.put("keyword3",keyword3);
        data.put("keyword4",keyword4);
        data.put("remark",remark);

        jsonObject.put("data", data);

        String string = null;
        try {
            string = WebUtil.sendPostJsonStr(templtUrl, jsonObject.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject result1 = JSONObject.parseObject(string);
        int errcode = result1.getIntValue("errcode");
        if(errcode == 0){
            // 发送成功
            System.out.println("发送成功");
        } else {
            // 发送失败
            System.out.println("发送失败");
        }
    }

    @Override
    public AjaxResult getDetail(Long reportId) {
        TbWorkReport workReport = baseMapper.selectById(reportId);
        SysUser createUser = userService.selectUserByUserName(workReport.getCreateBy());
        workReport.setSendUserName(userService.getUserListByIds(workReport.getSendUser()));
        workReport.setTitle(DateUtil.format(workReport.getReportDate(),"yyyy年MM月dd日")+"工作汇报");
        workReport.setDeptName(deptService.selectDeptById(createUser.getDeptId()).getDeptName());
        return AjaxResult.success(workReport);
    }

    @Override
    public AjaxResult removeWorkReport(Long workReportId) {
        List<TbReportUser> reportUserList = reportUserService.list(new QueryWrapper<TbReportUser>().eq("report_id",workReportId).eq("is_read",1));
        if (reportUserList!=null && reportUserList.size()>0){
            return AjaxResult.error(507,"该条工作汇报已读，无法删除！");
        }
        baseMapper.deleteById(workReportId);
        return AjaxResult.success();
    }

}
